//
//  BrandViewController.m
//  B_WatchHome
//
//  Created by dllo on 15/12/25.
//  Copyright © 2015年 DHF. All rights reserved.
//

#import "BrandViewController.h"
#import <Masonry.h>
#import "AppTools.h"
#import "BrandModel.h"
#import "BrandTableViewCell.h"
#import "BrandDetailViewController.h"

#define WIDTH ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface BrandViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate>

@property (nonatomic, strong)UITableView *myTableView;

@end

@implementation BrandViewController


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.myTableView reloadData];
}

//- (void)viewWillDisappear:(BOOL)animated{
//    self.searchDC.active = NO;
//    NSLog(@" 00000");
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.searchArray = [NSMutableArray array];
    
    self.mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, WIDTH, (40 * HEIGHT) / 667)];
    [self.view addSubview:self.mySearchBar];
    self.mySearchBar.delegate = self;
    [self.mySearchBar setPlaceholder:@"搜索品牌"];
    
    self.searchDC = [[UISearchDisplayController alloc] initWithSearchBar:self.mySearchBar contentsController:self];
    self.searchDC.active = NO;
    
    self.searchDC.searchResultsDataSource = self;
    self.searchDC.searchResultsDelegate = self;
    
    [self.searchDC.searchResultsTableView registerClass:[BrandTableViewCell class] forCellReuseIdentifier:@"search"];
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, (64 + self.mySearchBar.frame.size.height), WIDTH, (563*HEIGHT)/667) style:UITableViewStylePlain];
//    self.myTableView.backgroundColor = [UIColor greenColor];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    
    [self.view addSubview:self.myTableView];
    
    [self.myTableView registerClass:[BrandTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    self.bigDic = [NSMutableDictionary dictionary];
    
    self.bigArray = [NSMutableArray array];
    
    NSString *urlStr = @"http://www.xbiao.com/app/brandlist";
    
    [AppTools getDataWithURL:urlStr Block:^(id result) {
        NSMutableDictionary *dic = result;
        self.bigArray = dic.allKeys;
        
        for (int i = 0; i < self.bigArray.count; i++) {
            
            self.sectionArray = [NSMutableArray array];
            
            for (NSMutableDictionary *keyDic in [dic objectForKey:self.bigArray[i]]) {
                
                BrandModel *model = [[BrandModel alloc] init];
                [model setValuesForKeysWithDictionary:keyDic];
                [self.sectionArray addObject:model];
                
            }
            
            [self.bigDic setValue:self.sectionArray forKey:self.bigArray[i]];
        }
        
        self.keysArray = [NSMutableArray arrayWithArray:self.bigDic.allKeys];
        
        //给数组排序
        [self.keysArray sortUsingSelector:@selector(compare:)];
        [self.myTableView reloadData];
        
    }];
    

}

////搜索框
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.searchArray removeAllObjects];
    self.importantKey = searchText;
    for (NSString *key in self.keysArray) {
        NSMutableArray *array = [self.bigDic objectForKey:key];
        for (BrandModel *model in array) {
            if ([model.name rangeOfString:searchText].location != NSNotFound) {
                [self.searchArray addObject:model];
            }
        }
    }
}



-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return YES;
    
}

-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return YES;
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        
        return nil;
    }else
    {
        
       
        return self.keysArray;
        
    }
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        
        return 1;
    }
    else
    {
        
        return self.keysArray.count;
        
    }
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        
        return self.searchArray.count;
        
    }
    else
    {
        
        
        NSString *str = [self.keysArray objectAtIndex:section];
        
        NSMutableArray *array = [self.bigDic objectForKey:str];
        
        return array.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"search";
    static NSString *cellIndentifier = @"cell";
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        
        BrandTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        BrandModel *model = [self.searchArray objectAtIndex:indexPath.row];
        
        cell.importantKey = self.importantKey;
        
        cell.model = model;
        
        return cell;
        
    }
    else{

    BrandTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
    NSString *key = [self.keysArray objectAtIndex:indexPath.section];
    
    self.arrayRow = [NSMutableArray arrayWithArray:[self.bigDic objectForKey:key]];
    
        NSLog(@"%ld", self.arrayRow.count);
    BrandModel *model = [self.arrayRow objectAtIndex:indexPath.row];
    cell.model = model;
        //选中时有置灰效果，离开时消失选中效果
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return (20*HEIGHT)/667;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return nil;
    }
    else
    {
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, (100*WIDTH)/375, (20*HEIGHT)/667)];
        label.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
        
        NSString *str = [self.keysArray objectAtIndex:section];
        
        NSString *strText = [NSString stringWithFormat:@"    %@",str];
        
        label.text = strText;
        
        return label;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    return (120*HEIGHT)/667;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        BrandDetailViewController *detailVC = [[BrandDetailViewController alloc] init];
        BrandModel *model = [self.searchArray objectAtIndex:indexPath.row];
        detailVC.model = model;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    else
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        BrandDetailViewController *detailVC = [[BrandDetailViewController alloc] init];
        NSString *key = [self.keysArray objectAtIndex:indexPath.section];
        self.arrayRow = [self.bigDic objectForKey:key];
        
        BrandModel *model = [self.arrayRow objectAtIndex:indexPath.row];
        detailVC.model = model;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
